//
//  OYAccessModel.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/3.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit

class OYAccessModel: NSObject ,NSCoding{
    
    /// 令牌
    var access_token: String?

    
    /// 过期时间
    var expires_in: TimeInterval = 0 {
        didSet {
            
            expireDate = Date().addingTimeInterval(expires_in)
        }
    }
    
    var expireDate: Date?
    
    var uid:Int64 = 0
    
    /// 昵称
    var screen_name: String?
    
    /// 头像地址
    var avatar_large: String?
    
    
    init(dict:[String:Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
     // MARK: -归档编码
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expireDate, forKey: "expireDate")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        aCoder.encode(uid, forKey: "uid")
        
    }
    
     // MARK: -解档编码
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expireDate = aDecoder.decodeObject(forKey: "expireDate") as? Date
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        uid = aDecoder.decodeInt64(forKey: "uid")

    }
    
     // MARK: -归档
    func saveUserAccount() {
        
        let filePath = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!) as NSString).appendingPathComponent("useraccount.archiver")
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
     // MARK: -解档
    class func loadUserAccount()->OYAccessModel?{
        let filePath = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!) as NSString).appendingPathComponent("useraccount.archiver")
        let userAccount =  NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? OYAccessModel
        return userAccount
    }
    
}
